<!--
 * @Author: qwlbwm 18370818801qwl./
 * @Date: 2023-09-14 09:09:09
 * @LastEditors: whereamazinghappen 306702547@qq.com
 * @LastEditTime: 2023-09-29 00:55:23
 * @FilePath: \checc-business-module-web-kgpt-dev\src\views\examineManage\boardVIew\zjContribution\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="container">
    <div style="padding-bottom: 10px">
      <el-date-picker
        v-model="searchFrom.age"
        type="year"
        style="width: 200px; margin-right: 10px"
        value-format="YYYY"
        placeholder="选择年份"
        :clearable="false"
        @change="ageChange"
      />
      <el-button type="primary" @click="editOrSaveBtn">{{
        state.editType == "edit" ? "编辑" : "保存"
      }}</el-button>
      <el-button type="success" @click="updateDataBtn">更新数据</el-button>
      <el-button type="primary" @click="exportExcel">导出Excel</el-button>
    </div>
    <div>
      <el-table
        :data="state.complex_table_list"
        :span-method="arraySpanMethod"
        :header-cell-style="headerCellStyle"
        v-loading="data.table_loading"
        style="width: 100%"
      >
        <el-table-column prop="indexType1" align="center" label="类指标">
          <template #default="scope">
            {{ scope.row.indexType1.name }}
          </template>
        </el-table-column>
        <el-table-column prop="indexType2" width="200px" align="center" label="模块指标">
          <el-table-column align="center" prop="indexType2">
            <template #default="scope">
              {{ scope.row.indexType2 ? scope.row.indexType2.name : "" }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="indexType2_li">
            <template #default="scope">
              {{ scope.row.indexType2_li ? scope.row.indexType2_li.name : "" }}
            </template>
          </el-table-column>
        </el-table-column>
        <!-- <el-table-column prop="indexType2_li" width="200px" align="center" label="模块指标2">
            <template #default="scope">
              {{ scope.row.indexType2_li ? scope.row.indexType2_li.name : '' }}
            </template>
          </el-table-column> -->
        <el-table-column prop="indexType3" align="center" label="子指标">
          <template #default="scope">
            {{ scope.row.indexType3 ? scope.row.indexType3.name : "" }}
          </template>
        </el-table-column>
        <el-table-column prop="annualScore" align="center" label="年度标准分值">
          <el-table-column prop="annualScore" align="center">
            <template #default="scope">
              {{ scope.row.annualScore }}
            </template>
          </el-table-column>
          <el-table-column prop="annualSumScore" align="center">
            <template #default="scope">
              {{ scope.row.annualSumScore }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column prop="degradeScore" align="center" label="分解合计">
          <el-table-column prop="degradeScore" align="center">
            <template #default="scope">
<!--              {{ scope.row.degradeSumScore }}--> <!-- 之前的取值-->
              {{ scope.row.degradeScore}}
            </template>
          </el-table-column>
          <el-table-column prop="degradeSumScore" align="center">
            <template #default="scope">
              {{ scope.row.degradeSumScore }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column
          :prop="'cs' + c.id"
          v-for="c in state.company_list"
          :key="c.id"
          align="center"
          width="120px"
          :label="c.companyName"
        >
          <template #default="scope">
            <!-- {{ scope.row['cs' + c.id].indexId  }}  -->
            <div v-if="scope.row['cs' + c.id] && scope.row['cs' + c.id].indexId">
              <div
                class="company-score"
                v-if="
                  state.editType == 'edit' || scope.row.indexType1.name !== '战略引领类'
                "
                @click="lookLpl(scope.row['cs' + c.id])"
              >
                {{ scope.row["cs" + c.id].score }}
              </div>
              <el-input
                v-else-if="
                  state.editType == 'save' && scope.row.indexType1.name == '战略引领类'
                "
                v-model="scope.row['cs' + c.id].score"
                style="width: 80px"
              ></el-input>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <decompose-detail v-model:visible="state.mxVisible" :handleRow="state.handleRow">
    </decompose-detail>
  </div>
</template>
<script lang="ts" setup>
import { getCompanyListRequest,getCompanyListRequest1, } from "@/views/examineManage/api/examineManage";
import * as api from "@/views/examineManage/api/zJexaminePlan";
import pubFc from "@/views/examineManage/utils";
import {ElMessage, ElMessageBox} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import decomposeDetail from "./decomposeDetail.vue";
import {tips} from "@/views/science/components/tips/tips";
const zjeharts = ref();
const searchFrom = reactive({
  //查询
  age: "",
});

// const refreshPage:any=inject('refreshPage', Function, true);
// let annualId=route.query.id;
onMounted(() => {
  doHandleYear();
  refreshPage();
});
let data = reactive<any>({
  table_loading: false,
});
const refreshPage = () => {
  state.complex_table_list = [];
  state.company_list = [];
  state.complex_list = [];
  getComxlist();
};

let state = reactive<any>({
  table_list: [],
  complex_list: [],
  complex_table_list: [],
  company_list: [],
  rowSpan1: {},
  editType: "edit",
  mxVisible: false,
  handleRow: null,
});
const lookLpl = (data) => {
  console.log(data);
  //    api.degradeDetailRequest(data).then(res=>{
  //        console.log(res);
  //    })
  state.handleRow = data;
  state.mxVisible = true;
};
const updateDataBtn = () => {
  ElMessageBox.confirm("确定要更新数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api.updateScoreZjdRequest(searchFrom).then((res) => {
      data.table_loading = true;

      refreshPage();
      data.table_loading = false;

    });
  });

};
const editOrSaveBtn = () => {
  if (state.editType == "edit") {
    state.editType = "save";
  } else {
    let params: any = [];
    state.complex_table_list.map((item: any) => {
      state.company_list.map((cl) => {
        if (item[`cs${cl.id}`] && item[`cs${cl.id}`].indexId) {
          params.push(item[`cs${cl.id}`]);
        }
      });
    });
    api.saveScoreZjdRequest(params).then((res) => {
      ElMessage.success("成功保存");
      state.editType = "edit";
      refreshPage();
    });
  }
};
const exportExcel = () => {
  ElMessageBox.confirm("确定要批量导出吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api.exportZjdRequest({
      ...searchFrom,
    }).then((res) => {
      console.log(res, 'exportExcel')
      if (res.data instanceof Blob) {
        const reader = new FileReader();
        reader.readAsArrayBuffer(res.data);
        reader.onload = () => {
          const { data, headers } = res;
          try {
            const enc = new TextDecoder('utf-8');
            const msg = new Uint8Array(reader.result as ArrayBuffer);
            const errJson = JSON.parse(enc.decode(msg)) as any;
            if(errJson.code == 500) tips(errJson.msg || '该组数据检出异常，不能导出', "warning");
            else pubFc.downloadFunc(data, headers);
          } catch {
            pubFc.downloadFunc(data, headers);
          }
        }
      }
    }).catch(err =>{

    });
  });
};

const getComxlist = () => {
  //获取复杂的列表数据
  getCompanylist().then((res) => {
    zjconBoardlist();
  });
};
const getCompanylist = () => {
  return new Promise((resolve) => {
    // getCompanyListRequest({}).then((res) => {//获取全部公司列表
    getCompanyListRequest1(searchFrom).then((res) => {//获取单个公司列表
      state.company_list = res.data.data;
      resolve(true);
    });
  });
};
const ageChange = () => {
  refreshPage();
};
const doHandleYear = () => {
  var myDate = new Date();
  searchFrom.age = myDate.getFullYear() + "";
};

const zjconBoardlist = () => {

  data.table_loading = true;
  api.indexDecomposeRequest(searchFrom).then((res) => {
    // state.complex_list=res.data.data;
    dealDataBefore(res.data.data);
    dealDataRowCol();
    state.complex_table_list = state.complex_list;

    data.table_loading = false;
  }).catch(() =>{
    data.table_loading = false;
  })
};
const dealDataRowCol = () => {
  //处理合并行或合并列
  let rowSpan1: any = {},
    rowSpan2: any = {},
    rowSpan2_li: any = {};
  let copy_item: any = {},
    copy_item2: any = {},
    copy_item2_li: any = {};
  state.complex_list.map((item) => {
    if (item.indexType1 && item.indexType1.id) {
      if (rowSpan1[item.indexType1.id]) {
        copy_item.rowSpan1 += 1;
        rowSpan1[item.indexType1.id] += 1;
      } else {
        item.rowSpan1 = 1;
        copy_item = item;
        rowSpan1[item.indexType1.id] = 1;
      }
    }
    if (item.indexType2 && item.indexType2.id) {
      if (rowSpan2[item.indexType2.id]) {
        copy_item2.rowSpan2 += 1;
        rowSpan2[item.indexType2.id] += 1;
      } else {
        item.rowSpan2 = 1;
        copy_item2 = item;
        rowSpan2[item.indexType2.id] = 1;
      }
    }
    if (item.indexType2_li && item.indexType2_li.id) {
      if (rowSpan2_li[item.indexType2_li.id]) {
        copy_item2_li.rowSpan2_li += 1;
        rowSpan2_li[item.indexType2_li.id] += 1;
      } else {
        item.rowSpan2_li = 1;
        copy_item2_li = item;
        rowSpan2_li[item.indexType2_li.id] = 1;
      }
    }
  });
  // console.log('state.complex_list', state.complex_list)
};
const dealDataBefore = (arr) => {
  let obj: any = {};
  for (let i = 0, it; (it = arr[i]); i++) {
    obj.indexType1 = { name: it.name, id: it.id, indexType: 1 };
    if (it.children) {
      for (let i2 = 0, it2; (it2 = it.children[i2]); i2++) {
        obj.indexType2 = { name: it2.name, id: it2.id, indexType: 2, children: [] };
        obj.indexType2_li = null;
        state.company_list.map((cp) => {
          obj[`cs${cp.id}`] = {
            score: "",
            indexId: "",
            companyId: cp.id,
          };
        });
        if (it2.children) {
          for (let i3 = 0, it3; (it3 = it2.children[i3]); i3++) {
            if (it3.indexType == "2") {
              // obj.indexType2.children.push({name:it3.name,indexType:2})
              obj.indexType2_li = { name: it3.name, id: it3.id, indexType: 2 };
              if (it3.children) {
                for (let i4 = 0, it4; (it4 = it3.children[i4]); i4++) {
                  obj.indexType3 = { name: it4.name, id: it4.id, indexType: 3 };
                  obj.annualScore = it4.score;
                  obj.annualSumScore = it.score;
                  obj.degradeScore = it4.degradeScore;
                  obj.degradeSumScore = it.degradeScore;
                  if (it4.companyScoreList) {
                    it4.companyScoreList.map((cs) => {
                      obj[`cs${cs.companyId}`] = {
                        score: cs.score,
                        indexId: it4.id,
                        companyId: cs.companyId,
                      };
                    });
                  }
                  state.complex_list.push(JSON.parse(JSON.stringify(obj)));
                }
              } else {
                obj.indexType3 = null;
                obj.annualScore = null;
                obj.annualSumScore = it.score;
                obj.degradeScore = null;
                obj.degradeSumScore = it.degradeScore;
                state.company_list.map((cp) => {
                  obj[`cs${cp.id}`] = {
                    score: "",
                    indexId: "",
                    companyId: cp.id,
                  };
                });
                state.complex_list.push(JSON.parse(JSON.stringify(obj)));
              }
            } else {
              obj.indexType3 = { name: it3.name, indexType: 3, id: it3.id };
              obj.annualScore = it3.score;
              obj.annualSumScore = it.score;
              obj.degradeScore = it3.degradeScore;
              obj.degradeSumScore = it.degradeScore;
              if (it3.companyScoreList) {
                it3.companyScoreList.map((cs) => {
                  obj[`cs${cs.companyId}`] = {
                    score: cs.score,
                    indexId: it3.id,
                    companyId: cs.companyId,
                  };
                });
              }
              state.complex_list.push(JSON.parse(JSON.stringify(obj)));
            }
          }
        } else {
          obj.indexType3 = null;
          obj.annualScore = null;
          obj.annualSumScore = 0;
          obj.degradeScore = "";
          obj.degradeSumScore = "";
          state.company_list.map((cp) => {
            obj[`cs${cp.id}`] = {
              score: "",
              indexId: "",
              companyId: cp.id,
            };
          });
          state.complex_list.push(JSON.parse(JSON.stringify(obj)));
        }
      }
    } else {
      obj.indexType2 = null;
      obj.indexType3 = null;
      obj.annualScore = null;
      state.complex_list.push(JSON.parse(JSON.stringify(obj)));
    }
  }
};
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  //正常行也不正常
  if (columnIndex === 0) {
    //类指标
    return {
      rowspan: row.rowSpan1 || 0,
      colspan: 1,
    };
  } else if (columnIndex === 1) {
    //模块指标
    return {
      rowspan: row.rowSpan2 || 0,
      colspan: row.indexType2_li ? 1 : 2,
    };
  } else if (columnIndex === 2) {
    if (row.indexType2_li) {
      return {
        rowspan: row.rowSpan2_li || 0,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  } else if (columnIndex === 5) {
    //年度标准分值

    return {
      rowspan: row.rowSpan1 || 0,
      colspan: 1,
    };
  } else if (columnIndex === 7) {
    //年度标准分值

    return {
      rowspan: row.rowSpan1 || 0,
      colspan: 1,
    };
  }
};
const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (rowIndex == 1) {
    return { display: "none" };
  }
};
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
  overflow-y: auto;
}
.company-score {
  cursor: pointer;
}
.company-score:hover {
  color: #0093f5;
}
:deep(.el-dialog__body) {
  padding: 0;
}
</style>
